<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 获取 form 表单实例，调用表单的方法
const ruleFormRef = ref<FormInstance>()
    // 表单数据对象
    const ruleForm = reactive({
        password: '',
        username: '',

    })

    const loading = ref(false)
    // 表单验证规则
    const rules = reactive<FormRules<typeof ruleForm>>({
        username: [{ required:true, message:'请输入用户名', trigger: 'change' }],
        password: [{ required:true, message:'请输入密码', trigger: 'change' }],
    })


    const submit = () => {
        ruleFormRef.value?.validate((valid) => {
            if (valid) {
                const token = {
                    username:ruleForm.username,
                    password:ruleForm.password
                }
                ElMessage.success('登陆成功')
                localStorage.setItem('token',token)
                router.push('home')
            } else {
                console.log('校验失败')
            }
        })
    }
</script>

<template>
  <div class="login">
    <div class="loginIn">
      <h3>登录页面</h3>
      <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            status-icon
        >
            <el-form-item prop="username">
                <el-input placeholder="用户名" v-model.number="ruleForm.username" />
            </el-form-item>

            <el-form-item prop="password">
                <el-input placeholder="密码" v-model="ruleForm.password" type="password" autocomplete="off" />
            </el-form-item>

            <el-form-item>
                <el-button :loading="loading" type="primary"  @click="submit" style="width: 100%">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login{
    width: 100vw; 
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    .loginIn{
    width: 300px;
    background: #eee;
    padding: 15px;
    border-radius: 5px;
    text-align: center;
        h3{
            text-align: center;
            margin-bottom: 15px;
        }
}
}
</style>
